#include "exportstateadapter.h"
#include "mainwindow.h"
#include "mergedexportmanager.h"
#include <QDebug>
#include <QStringList>

ExportStateAdapter::ExportStateAdapter(QObject* parent)
    : QObject(parent)
    , m_stateManager(nullptr)
    , m_uiSynchronizer(nullptr)
    , m_throttler(nullptr)
    , m_mainWindow(nullptr)
    , m_exportManager(nullptr)
    , m_exportButton(nullptr)
    , m_progressBar(nullptr)
    , m_statusLabel(nullptr)
{
    // 创建核心组件
    m_stateManager = new UnifiedExportStateManager(this);
    m_throttler = new StateUpdateThrottler(this);
    
    // 设置连接
    setupConnections();
    
}

ExportStateAdapter::~ExportStateAdapter()
{
    if (m_uiSynchronizer) {
        delete m_uiSynchronizer;
        m_uiSynchronizer = nullptr;
    }
}

void ExportStateAdapter::initialize(MainWindow* mainWindow, MergedExportManager* exportManager)
{
    m_mainWindow = mainWindow;
    m_exportManager = exportManager;
    
    // 更新导出管理器连接
    updateExportManager();
    
    m_initialized = true;
}

void ExportStateAdapter::setUIComponents(QPushButton* exportButton, QProgressBar* progressBar, QLabel* statusLabel)
{
    m_exportButton = exportButton;
    m_progressBar = progressBar;
    m_statusLabel = statusLabel;
    
    // 创建UI同步器
    if (m_uiSynchronizer) {
        delete m_uiSynchronizer;
    }
    
    m_uiSynchronizer = new ExportUIStateSynchronizer(
        m_stateManager, 
        m_exportButton, 
        m_progressBar, 
        m_statusLabel, 
        this
    );
    
    // 配置UI同步器
    m_uiSynchronizer->setAnimationEnabled(m_animationEnabled);
    m_uiSynchronizer->setTooltipEnabled(m_tooltipEnabled);
    
}

void ExportStateAdapter::setFiles(const QStringList& filePaths)
{
    m_currentFiles = filePaths;
    m_stateManager->setFiles(filePaths);
}

void ExportStateAdapter::addFile(const QString& filePath)
{
    if (!m_currentFiles.contains(filePath)) {
        m_currentFiles.append(filePath);
        m_stateManager->addFile(filePath);
    }
}

void ExportStateAdapter::removeFile(const QString& filePath)
{
    if (m_currentFiles.removeOne(filePath)) {
        m_stateManager->removeFile(filePath);
    }
}

void ExportStateAdapter::clearFiles()
{
    m_currentFiles.clear();
    m_stateManager->clearFiles();
}

void ExportStateAdapter::startExport()
{
    if (!canExport()) {
        return;
    }
    
    m_stateManager->startExport();
    emit exportRequested();
}

void ExportStateAdapter::cancelExport()
{
    m_stateManager->cancelExport();
    emit exportCancelled();
}

void ExportStateAdapter::retryExport()
{
    if (m_stateManager->currentState() == UnifiedExportStateManager::ExportState::Failed) {
        m_stateManager->setFiles(m_currentFiles); // 重新设置文件
        startExport();
        emit exportRetried();
    }
}

bool ExportStateAdapter::canExport() const
{
    return m_stateManager->canExport();
}

bool ExportStateAdapter::isExporting() const
{
    return m_stateManager->isExporting();
}

UnifiedExportStateManager::ExportState ExportStateAdapter::currentState() const
{
    return m_stateManager->currentState();
}

void ExportStateAdapter::setAnimationEnabled(bool enabled)
{
    m_animationEnabled = enabled;
    if (m_uiSynchronizer) {
        m_uiSynchronizer->setAnimationEnabled(enabled);
    }
}

void ExportStateAdapter::setTooltipEnabled(bool enabled)
{
    m_tooltipEnabled = enabled;
    if (m_uiSynchronizer) {
        m_uiSynchronizer->setTooltipEnabled(enabled);
    }
}

void ExportStateAdapter::setThrottleEnabled(bool enabled)
{
    m_throttleEnabled = enabled;
    if (m_throttler) {
        m_throttler->setEnabled(enabled);
    }
}

void ExportStateAdapter::setupConnections()
{
    // 连接统一状态管理器信号
    connect(m_stateManager, &UnifiedExportStateManager::stateChanged,
            this, &ExportStateAdapter::onStateChanged);
    connect(m_stateManager, &UnifiedExportStateManager::fileStateChanged,
            this, &ExportStateAdapter::onFileStateChanged);
    connect(m_stateManager, &UnifiedExportStateManager::exportStarted,
            this, &ExportStateAdapter::onExportStarted);
    connect(m_stateManager, &UnifiedExportStateManager::exportProgressChanged,
            this, &ExportStateAdapter::onExportProgressChanged);
    connect(m_stateManager, &UnifiedExportStateManager::exportCompleted,
            this, &ExportStateAdapter::onExportCompleted);
    connect(m_stateManager, &UnifiedExportStateManager::exportFailed,
            this, &ExportStateAdapter::onExportFailed);
    connect(m_stateManager, &UnifiedExportStateManager::exportCancelled,
            this, &ExportStateAdapter::onExportCancelled);
    connect(m_stateManager, &UnifiedExportStateManager::errorOccurred,
            this, &ExportStateAdapter::onErrorOccurred);
    
    // 连接节流器信号
    connect(m_throttler, &StateUpdateThrottler::stateUpdateRequested,
            this, &ExportStateAdapter::onStateUpdateRequested);
    
}

void ExportStateAdapter::updateExportManager()
{
    if (!m_exportManager) {
        return;
    }
    
    // 这里可以添加与导出管理器的连接逻辑
    // 例如连接进度更新信号等
}

void ExportStateAdapter::handleExportError(const UnifiedExportStateManager::ExportError& error)
{
    QString errorMessage = formatErrorMessage(error);
    
    switch (error.severity) {
        case UnifiedExportStateManager::ErrorSeverity::Info:
            emit showToast(errorMessage);
            break;
        case UnifiedExportStateManager::ErrorSeverity::Warning:
            emit showToast("警告: " + errorMessage);
            break;
        case UnifiedExportStateManager::ErrorSeverity::Error:
            emit showError(errorMessage);
            break;
        case UnifiedExportStateManager::ErrorSeverity::Critical:
            emit showError("严重错误: " + errorMessage);
            break;
    }
    
}

QString ExportStateAdapter::formatErrorMessage(const UnifiedExportStateManager::ExportError& error) const
{
    QString message = error.message;
    if (!error.suggestion.isEmpty()) {
        message += "\n建议: " + error.suggestion;
    }
    if (error.canRetry) {
        message += "\n可以重试";
    }
    return message;
}

void ExportStateAdapter::onStateChanged(UnifiedExportStateManager::ExportState newState, 
                                       UnifiedExportStateManager::ExportState oldState)
{
    
    emit stateChanged(newState);
    emit canExportChanged(canExport());
    
    // 通过节流器处理状态更新
    if (m_throttleEnabled) {
        StateUpdateThrottler::StateUpdateRequest request(
            "state_change", 
            QVariant(static_cast<int>(newState)),
            1 // 高优先级
        );
        m_throttler->requestStateUpdate(request);
    }
}

void ExportStateAdapter::onFileStateChanged(UnifiedExportStateManager::FileState newState)
{
    emit canExportChanged(canExport());
}

void ExportStateAdapter::onExportStarted(int totalFiles)
{
    
    // 通知导出管理器开始导出
    if (m_exportManager && m_mainWindow) {
        // 这里可以调用实际的导出逻辑
        // 例如：m_exportManager->startExport(...)
    }
}

void ExportStateAdapter::onExportProgressChanged(int completed, int total, const QString& status)
{
    
    // 通知导出管理器更新进度
    if (m_exportManager) {
        // 这里可以调用导出管理器的进度更新方法
    }
}

void ExportStateAdapter::onExportCompleted()
{
    emit showSuccess("导出完成！");
}

void ExportStateAdapter::onExportFailed(const QString& error)
{
    emit showError("导出失败: " + error);
}

void ExportStateAdapter::onExportCancelled()
{
    emit showToast("导出已取消");
}

void ExportStateAdapter::onErrorOccurred(const UnifiedExportStateManager::ExportError& error)
{
    handleExportError(error);
}

void ExportStateAdapter::onStateUpdateRequested(const StateUpdateThrottler::StateUpdateRequest& request)
{
    
    // 根据请求类型处理状态更新
    if (request.type == "state_change") {
        // 处理状态变化
        int newState = request.data.toInt();
    }
}
